package com.pnk087.hr.dao.jpa;

import com.pnk087.hr.dao.UserDao;
import com.pnk087.hr.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManagerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: khanh
 * Date: 6/22/11 3:25 PM
 */
@Repository("userDao")
public class JpaUserDao extends JpaGenericDao<User> implements UserDao {

   @Autowired
   public JpaUserDao(final EntityManagerFactory entityManagerFactory) {
      super(User.class);
      super.setEntityManagerFactory(entityManagerFactory);
   }

   public List<User> findActiveUsers() {
      return this.getJpaTemplate().findByNamedQuery("User.findActiveUser");
   }

   public User findByUsername(final String username) {
      Map<String, String> params = new HashMap<String, String>();
      params.put("username", username);

      List<User> result = this.getJpaTemplate().findByNamedQueryAndNamedParams("User.findByUsername", params);
      if (result == null || result.size() != 1) {
         throw new ObjectRetrievalFailureException(User.class, username);
      }

      return result.get(0);
   }
}
